package com.zhihesj.anan;

import org.junit.Test;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import sun.net.www.protocol.http.HttpURLConnection;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author anan.
 * @version 1.0
 * @create 2021-06-12 12-20
 */
public class AnanMain {

	@Test
	public  void test() throws Exception {
		String username="gicinterfacetest@gmq.com";
		String password="123456";
		String url11="http://192.168.90.11:90/servlets/binserv/Rest";
		String url12="http://192.168.90.12:90/servlets/binserv/Rest";
		String url13="http://192.168.90.13:90/servlets/binserv/Rest";
		String url14="http://192.168.90.14:90/servlets/binserv/Rest";
		String url15="http://192.168.90.15:90/servlets/binserv/Rest";
		String url98="http://60.12.34.249:98/servlets/binserv/Rest";
		String url42="http://10.10.1.42:99/servlets/binserv/Rest";
		String url174="http://122.228.128.174:99/servlets/binserv/Rest";
//        String parmes="{\n" +
//                "\t\"table\": \"C_V_VOUCHERS\",\n" +
//                "\t\"count\": false,\n" +
//                "\t\"params\": {\n" +
//                "\t\t\"column\": \"VOUCHERS_NO\",\n" +
//                "\t\t\"condition\": \"GW2011200000001\"\n" +
//                "\t}\n" +
//                "}";

		String parmes="{\n" +
			"\t\"BIRTHDAY\": \"20200401\",\n"+
			"\t\"CARDNO\": \"13974563126\",\n"+
			"\t\"C_CUSTOMER_ID__NAME\": \"株洲总经销商\",\n"+
			"\t\"C_INTEGRALAREA_ID__NAME\": \"株洲\",\n"+
			"\t\"C_STORE_ID__NAME\": \"湖南洪江黔城店\",\n"+
			"\t\"C_VIPTYPE_ID__NAME\": \"株洲VIP卡\",\n"+
			"\t\"HR_EMPLOYEE_ID__NO\": \"ZZHHJZ001\",\n"+
			"\t\"ISACTIVE\": \"Y\",\n"+
			"\t\"MOBIL\": \"13974563126\",\n"+
			"\t\"NOW_GUIDE_ID__NO\": \"ZZHHJZ001\",\n"+
			"\t\"NOW_STORE_ID__NAME\": \"湖南洪江黔城店\",\n"+
			"\t\"OPENCARDDATE\": \"20210401\",\n"+
			"\t\"SERVICE_OPEN_ID\": \"oFLLB0oeqUSVMrL2GW1qu25cspk1\",\n"+
			"\t\"SEX\": \"M\",\n"+
			"\t\"VIPNAME\": \"蒋1111\",\n"+
			"\t\"id\": \"2017781\",\n"+
			"\t\"table\": \"C_VIP\" \n"+
			"}";

		// 组成业务数据
		// 60.12.34.249:98
		String str11=rest(url11,username,password,"ObjectModify",parmes);
		System.out.println(str11);
//        String str12=rest(url12,username,password,"Query",parmes);
//        System.out.println(str12);
//        String str13=rest(url13,username,password,"Query",parmes);
//        System.out.println(str13);
//        String str14=rest(url14,username,password,"Query",parmes);
//        System.out.println(str14);
//        String str15=rest(url15,username,password,"Query",parmes);
//        System.out.println(str15);
        String str98=rest(url98,username,password,"Query",parmes);
        System.out.println(str98);
//        String str42=rest(url42,username,password,"Query",parmes);
//        System.out.println(str42);
//        String str174=rest(url174,username,password,"Query",parmes);
//        System.out.println(str174);
	}


	public static JSONArray createTras(String command, String cmdparam) throws JSONException {
		JSONObject tra=new JSONObject();
		tra.put("id", 112);
		tra.put("command",command);
		// tra.put("params",  new JSONObject(cmdparam));
		tra.accumulate("params",  new JSONObject(cmdparam));
		System.out.println("===tra===="+tra.toString());
		JSONArray ja=new JSONArray();
		ja.put(tra);
		System.out.println("----请求数据---"+ja.toString());
		return ja;
	}

	public static String rest(String url,String sipKey,String secret,String command,String cmdparam)throws Exception{
		return rest(url,sipKey,secret,createTras(command,cmdparam));
	}

	// 数据加密

	public static String rest(String url,String sipKey,String secret,JSONArray tras) throws Exception{
		SimpleDateFormat a=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		a.setLenient(false);
		String tt= a.format(new Date());

//    	  Calendar beforeTime = Calendar.getInstance();
//    	  beforeTime.add(Calendar.MINUTE, -20);// 5分钟之前的时间
//    	  Date beforeD = beforeTime.getTime();
//    	  String tt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(beforeD);

		String m=MD5(secret);
		HashMap<String, String> params =new HashMap<String, String>();
		params.put("sip_appkey",sipKey);
		params.put("sip_timestamp", tt);
		System.out.println("-----请求时间------"+tt);
		params.put("sip_sign",MD5(sipKey+tt+m));
		params.put("transactions", tras.toString());
		JSONObject object=new JSONObject();
		object.accumulate("sip_appkey",sipKey);
		object.accumulate("sip_timestamp", tt);
		object.accumulate("sip_sign",MD5(sipKey+tt+m));
		object.put("transactions", tras);
		System.out.println("-------params----"+object.toString());
//          String vh=sendRequest(url,object,"POST");
		String vh=sendRequest(url,params,"POST");
		return vh;
	}


	//发送数据

	public static String sendRequest(String apiURL, Map<String, String> params, String method) throws Exception {

		String queryString = (null == params) ? "" : delimit(params.entrySet(),true );
		System.out.println("-----请求地址-----apiURL:"+apiURL);
		System.out.println("-----请求参数----queryString:"+queryString);
		System.out.println("-----请求方法----"+method);
		HttpURLConnection conn = (HttpURLConnection) new URL(apiURL).openConnection();
		conn.setConnectTimeout(6* 1000);
		conn.setRequestMethod(method);
		conn.setDoOutput(true);
		conn.connect();
		conn.getOutputStream().write(queryString.getBytes());
		String charset = getChareset(conn.getContentType());
		if (conn.getResponseCode() != 200) throw new Exception("请求url失败");
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
		StringBuffer buffer = new StringBuffer();
		String line;
		while ((line = reader.readLine()) != null) {
			buffer.append(line);
		}

		reader.close();
		conn.disconnect();
		String msg= buffer.toString();

		return msg;
	}



	public static String getChareset(String contentType) {
		int i = contentType == null ? -1 : contentType.indexOf("charset=");
		return i == -1 ? "UTF-8" : contentType.substring(i + 8);
	}

	// 生成querystring
	public  static String delimit(Collection<Map.Entry<String, String>> entries,
								  boolean doEncode) throws Exception {
		if (entries == null || entries.isEmpty()) {
			return null;
		}
		StringBuffer buffer = new StringBuffer();
		boolean notFirst = false;
		for (Map.Entry<String, ?> entry : entries) {
			if (notFirst) {
				buffer.append("&");
			} else {
				notFirst = true;
			}
			Object value = entry.getValue();
			if(value==null)value="";
			//             buffer.append(entry.getKey()).append("=").append(value);
			buffer.append(doEncode? URLEncoder.encode(entry.getKey(), "UTF8"):entry.getKey()).append("=").append(
				doEncode ? URLEncoder.encode(value.toString(), "UTF8") : value);
		}
		System.out.println("======transactions====="+buffer.toString());
		return buffer.toString();
	}
	/*对字符串MD5加密*/
	public static String MD5(String s){
		String r="";
		try{
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(s.getBytes());
			byte b[]=md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if(i<0) i+= 256;
				if(i<16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			r=buf.toString();
		}catch(Exception e){
		}
		return r;
	}

}
